<template>
  <view class="personal-data">
    <!-- 导航栏 -->

    <!-- 头像区域 -->
    <view class="avatar-container">
      <view class="avatar-wrapper" @click="chooseAvatar">
        <image 
          :src="userInfo.avatarUrl || defaultAvatar" 
          class="avatar-img"
          mode="aspectFill"
        ></image>
        <u-icon name="camera" class="camera-icon" color="#ffffff"></u-icon>
      </view>
      <view class="avatar-tip">点击更换头像</view>
    </view>

    <!-- 个人信息列表 -->
    <u-cell-group>
      <u-cell-item 
        title="昵称" 
        :value="userInfo.nickname || '未设置'" 
        :title-style="{ marginLeft: '10rpx' }"
        @click="editInfo('nickname')"
      >
        <u-icon slot="right-icon" name="arrow-right" color="#969799"></u-icon>
      </u-cell-item>
      
      <u-cell-item 
        title="手机号" 
        :value="formatPhone(userInfo.phone)" 
        :title-style="{ marginLeft: '10rpx' }"
        @click="showPhoneTip"
      >
        <u-icon slot="right-icon" name="arrow-right" color="#969799"></u-icon>
      </u-cell-item>
      
      <u-cell-item 
        title="微信号" 
        :value="userInfo.wechatId || '未设置'" 
        :title-style="{ marginLeft: '10rpx' }"
        @click="editInfo('wechatId')"
      >
        <u-icon slot="right-icon" name="arrow-right" color="#969799"></u-icon>
      </u-cell-item>
      
      <u-cell-item 
        title="地区" 
        :value="userInfo.region || '未设置'" 
        :title-style="{ marginLeft: '10rpx' }"
        @click="editRegion"
      >
        <u-icon slot="right-icon" name="arrow-right" color="#969799"></u-icon>
      </u-cell-item>
      
      <u-cell-item 
        title="个性签名" 
        :value="userInfo.signature || '未设置'" 
        :title-style="{ marginLeft: '10rpx' }"
        @click="editInfo('signature')"
      >
        <u-icon slot="right-icon" name="arrow-right" color="#969799"></u-icon>
      </u-cell-item>
    </u-cell-group>

    <!-- 编辑弹窗 -->
    <u-modal 
      v-model="showEditModal" 
      :title="editTitle" 
      :show-cancel="true"
      confirm-text="保存"
      cancel-text="取消"
      @confirm="saveEdit"
    >
      <u-input 
        v-model="editValue" 
        :placeholder="'请输入' + editTitle"
        :maxlength="editMaxlength"
        class="edit-input"
      ></u-input>
    </u-modal>

    <!-- 地区选择器 - 三级联动 -->
    <u-picker 
      v-model="showRegionPicker"
      :columns="regionColumns"
      @change="onRegionChange"
      @confirm="confirmRegion"
      @cancel="showRegionPicker = false"
      title="选择地区"
      :loading="regionLoading"
    ></u-picker>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 默认头像
      defaultAvatar: require('@/static/avater/4.png'),
      // 用户信息
      userInfo: {
        avatarUrl: '',
        nickname: '',
        phone: '',
        wechatId: '',
        region: '',
        signature: ''
      },
      // 编辑相关
      showEditModal: false,
      editField: '',
      editTitle: '',
      editValue: '',
      editMaxlength: 30,
      // 地区选择
      showRegionPicker: false,
      regionColumns: [], // 动态生成的地区列
      regionData: [], // 完整地区数据
      regionLoading: false, // 地区加载状态
      selectedProvince: '',
      selectedCity: '',
      selectedDistrict: ''
    };
  },
  
  onLoad() {
    // 从本地存储获取用户信息
    this.loadUserInfo();
    // 初始化地区数据
    this.initRegionData();
  },
  
  methods: {
    // 返回上一页
    navBack() {
      uni.navigateBack({
        delta: 1
      });
    },
    
    // 加载用户信息
    loadUserInfo() {
      const storedUser = uni.getStorageSync('userInfo');
      if (storedUser) {
        this.userInfo = { ...this.userInfo, ...storedUser };
      }
      // 获取手机号（从登录信息中）
      this.userInfo.phone = uni.getStorageSync('regPhone') || '';
    },
    
    // 选择头像
    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.userInfo.avatarUrl = res.tempFilePaths[0];
          this.saveUserInfo();
        }
      });
    },
    
    // 编辑信息
    editInfo(field) {
      this.editField = field;
      switch(field) {
        case 'nickname':
          this.editTitle = '昵称';
          this.editMaxlength = 16;
          break;
        case 'wechatId':
          this.editTitle = '微信号';
          this.editMaxlength = 20;
          break;
        case 'signature':
          this.editTitle = '个性签名';
          this.editMaxlength = 30;
          break;
      }
      this.editValue = this.userInfo[field] || '';
      this.showEditModal = true;
    },
    
    // 保存编辑
    saveEdit() {
      if (this.editValue.trim() || this.editField === 'signature') {
        this.userInfo[this.editField] = this.editValue.trim();
        this.saveUserInfo();
      }
      this.showEditModal = false;
    },
    
    // 初始化地区数据
    initRegionData() {
      // 实际项目中可以从接口获取完整地区数据
      // 这里使用模拟数据作为示例
      this.regionData = [
        {
          name: '北京市',
          cities: [
            {
              name: '北京市',
              districts: ['东城区', '西城区', '朝阳区', '丰台区', '石景山区', '海淀区', '顺义区']
            }
          ]
        },
        {
          name: '上海市',
          cities: [
            {
              name: '上海市',
              districts: ['黄浦区', '徐汇区', '长宁区', '静安区', '普陀区', '虹口区', '杨浦区']
            }
          ]
        },
        {
          name: '广东省',
          cities: [
            {
              name: '广州市',
              districts: ['越秀区', '海珠区', '荔湾区', '天河区', '白云区', '黄埔区', '番禺区']
            },
            {
              name: '深圳市',
              districts: ['福田区', '罗湖区', '南山区', '宝安区', '龙岗区', '盐田区']
            },
            {
              name: '珠海市',
              districts: ['香洲区', '斗门区', '金湾区']
            }
          ]
        },
        {
          name: '江苏省',
          cities: [
            {
              name: '南京市',
              districts: ['玄武区', '秦淮区', '建邺区', '鼓楼区', '浦口区', '栖霞区']
            },
            {
              name: '苏州市',
              districts: ['姑苏区', '虎丘区', '吴中区', '相城区', '吴江区', '常熟市', '张家港市']
            }
          ]
        }
      ];
      
      // 初始化省份列
      this.regionColumns[0] = this.regionData.map(province => province.name);
      
      // 如果已有地区信息，自动选中
      if (this.userInfo.region) {
        const regionArr = this.userInfo.region.split(' ');
        if (regionArr.length >= 3) {
          this.selectedProvince = regionArr[0];
          this.selectedCity = regionArr[1];
          this.selectedDistrict = regionArr[2];
          
          // 初始化城市和地区列
          this.updateCityColumn();
          this.updateDistrictColumn();
        }
      } else {
        // 默认选中第一个省份的第一个城市和地区
        this.selectedProvince = this.regionData[0].name;
        this.updateCityColumn();
      }
    },
    
    // 编辑地区
    editRegion() {
      this.showRegionPicker = true;
    },
    
    // 地区选择变化时更新下一级数据
    onRegionChange(e) {
      const { columnIndex, value } = e;
      this.regionLoading = true;
      
      // 模拟网络请求延迟
      setTimeout(() => {
        if (columnIndex === 0) {
          // 省份改变，更新城市列
          this.selectedProvince = value;
          this.updateCityColumn();
        } else if (columnIndex === 1) {
          // 城市改变，更新地区列
          this.selectedCity = value;
          this.updateDistrictColumn();
        } else if (columnIndex === 2) {
          // 地区改变
          this.selectedDistrict = value;
        }
        this.regionLoading = false;
      }, 300);
    },
    
    // 更新城市列
    updateCityColumn() {
      const province = this.regionData.find(item => item.name === this.selectedProvince);
      if (province && province.cities) {
        this.regionColumns[1] = province.cities.map(city => city.name);
        this.selectedCity = province.cities[0].name;
        this.updateDistrictColumn();
      } else {
        this.regionColumns[1] = [];
        this.regionColumns[2] = [];
      }
    },
    
    // 更新地区列
    updateDistrictColumn() {
      const province = this.regionData.find(item => item.name === this.selectedProvince);
      if (province && province.cities) {
        const city = province.cities.find(item => item.name === this.selectedCity);
        if (city && city.districts) {
          this.regionColumns[2] = city.districts;
          this.selectedDistrict = city.districts[0];
        } else {
          this.regionColumns[2] = [];
        }
      } else {
        this.regionColumns[2] = [];
      }
    },
    
    // 确认地区选择
  // 确认地区选择
  confirmRegion(e) {
    // 确保有足够的元素进行解构
    const [province = '', city = '', district = ''] = Array.isArray(e.value) ? e.value : [];
    if (province && city) {
      this.userInfo.region = district ? `${province} ${city} ${district}` : `${province} ${city}`;
      this.saveUserInfo();
    }
    this.showRegionPicker = false;
  },
    
    // 显示手机号提示
    showPhoneTip() {
      uni.showToast({
        title: '手机号不可修改',
        icon: 'none'
      });
    },
    
    // 保存用户信息到本地
    saveUserInfo() {
      uni.setStorageSync('userInfo', this.userInfo);
      uni.showToast({
        title: '保存成功',
        icon: 'none'
      });
    },
    
    // 格式化手机号
    formatPhone(phone) {
      if (!phone) return '未绑定';
      return phone.replace(/^(\d{3})(\d{4})(\d{4})$/, '$1****$3');
    }
  }
};
</script>

<style lang="scss" scoped>
.personal-data {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-top: 0;
}

/* 头像样式 */
.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 0;
  background-color: #ffffff;
  margin-bottom: 10rpx;

  .avatar-wrapper {
    position: relative;
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    overflow: hidden;
    margin-bottom: 20rpx;

    .avatar-img {
      width: 100%;
      height: 100%;
    }

    .camera-icon {
      position: absolute;
      bottom: 0;
      right: 0;
      background-color: rgba(0, 0, 0, 0.5);
      width: 40rpx;
      height: 40rpx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .avatar-tip {
    font-size: 26rpx;
    color: #969799;
  }
}

/* 列表样式 */
::v-deep u-cell-group {
  background-color: #ffffff;
  margin-bottom: 10rpx;

  u-cell-item {
    height: 100rpx;
    border-bottom: 1px solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }

    .u-cell-item__value {
      color: #606266;
      font-size: 28rpx;
    }
  }
}

/* 编辑输入框 */
.edit-input {
  width: 100%;
  margin-top: 20rpx;
}
</style>
